import React, {PureComponent} from 'react';
import ReactDOM from 'react-dom'
import {connect} from 'dva';
import {
    Form, Input, Button, Card, Select,Radio,Icon
} from 'antd';
import styles from '../../../routes/style.less';
import {message} from "antd/lib/index";
import constants from '../../../common/constants';

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const userInfoState = sessionStorage.getItem("userInfoState");
const {Option} = Select;
let uuid = 0;

@connect(state => ({
    submitting: state.attribute.loading,
}))
@Form.create()
export default class AttributeEdit extends PureComponent {
    state = {
        loading: false,
        attrVal: [{attr_value: ''}],
        keys: [],
        goodsType:[],
    };
    componentWillMount(){
        this.props.dispatch({
            type:'attributeEdit/queryGoodsType',
            callback:(response)=>{
                if(response.result===0){
                    this.setState({
                        goodsType:response.resultData.queryGoodsTypeName,
                    })
                }
            }
        })
    }
    componentDidMount() {
        const { record, editType } = this.props;
        const formInitValue = editType === 'add' ? '' : record;
        const init = editType === 'add' ? [] : formInitValue.attr_value.split(",");
        this.setState({
            keys: [...Array(init.length).keys()] || []
        })
    }

    handleParentModalVisible = (e) => {
        this.props.handleModalVisible();
    }

    handleSubmit = (editType,attr_id,attr_value_id,e) => {
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                const { form } = this.props;
                let attr = []; //定义一个数组用于存放属性值
                this.state.keys.map(function(k){
                    const val = form.getFieldValue(`val-${k}`);
                    attr.push(val);
                })
                const params = {
                    ...values,
                    //cat_id: this.props.record.cat_id,
                    attr: attr,
                    attr_id: attr_id,
                    attr_value_id: attr_value_id
                };
                this.props.dispatch({
                    type: `attributeEdit/${editType}`,
                    payload: params,
                    callback: (response) => {
                        if (response.result === 0) {
                            message.success('提交成功');
                            this.props.handleModalVisible();
                            this.props.handleModalSuccess(this.props.pagination);
                        } else {
                            message.success('提交失败');
                        }
                    }
                });
            }
        });
    }


    add = () => {
        let max = Math.max.apply(Math,this.state.keys) + 1;
        uuid++;
        const { form } = this.props;
        const keys = form.getFieldValue('keys');
        let nextKeys=[];
        if(max<0){
             nextKeys = keys.concat(uuid);
        }else{
             nextKeys = keys.concat(max);
        }
        this.setState({keys: nextKeys});
        form.setFieldsValue({
            keys: nextKeys,
        });
    }
    remove = (k) => {
        const { form } = this.props;
        const keys = form.getFieldValue('keys');
        // this.setState({keys: keys});
        if (keys.length === 1) {
            return;
        }
        form.setFieldsValue({
            keys: keys.filter(key => key !== k),
        });
        this.setState({keys: form.getFieldValue('keys')});
    }
    handleSelectChange=(e)=>{
        if(e===0){
            ReactDOM.findDOMNode(this.refs.addAttr).disabled = true;
        }else{
            ReactDOM.findDOMNode(this.refs.addAttr).disabled=false;
        }
    }
    render() {
        const {submitting, record, editType,cat_id,cat_name } = this.props;
        const {goodsType}=this.state;
        const {getFieldDecorator, getFieldValue} = this.props.form;
        const formInitValue = editType === 'add' ? '' : record;
        const attr_id = editType === 'add' ? '' : record.attr_id;
        const attr_value_id = editType === 'add' ? '' : record.attr_value_id;
        const submitFormLayout = {
            wrapperCol: {
                xs: {span: 24, offset: 0},
                sm: {span: 10, offset: 7},
            },
        };

        const formItemLayout = {
            labelCol: {
                xs: { span: 20 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 10 },
            },
        };
        const formItemLayoutWithOutLabel = {
            wrapperCol: {
                xs: { span: 24, offset: 0 },
                sm: { span: 20, offset: 4 },
            },
        };
        const SelectOption=goodsType.map((value,index)=>{
            return (<Option key={value.cat_id}  value={value.cat_id}>{value.cat_name}</Option>);
        })
        const init = editType === 'add' ? [] : (formInitValue.attr_value===''?[]:formInitValue.attr_value.split(","));
        getFieldDecorator('keys', { initialValue: init.length===0?[] : [...Array(init.length).keys()] });
        const keys = getFieldValue('keys');
        const formItems = keys.map((k, index) => {
            return (
                <FormItem
                    {...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
                    label={index === 0 ? '属性值' : ''}
                    required={false}
                    key={k}
                >
                    {getFieldDecorator(`val-${k}`, {
                        initialValue:  init[k] || '',
                        validateTrigger: ['onChange', 'onBlur'],
                        rules: [{
                            required: true,
                            whitespace: true,
                            message: "请输入属性值或删除改行",
                        }],
                    })(
                        <Input placeholder="属性值" style={{ width: '100%', marginRight: 8 }} />
                    )}
                    {keys.length > 1 ? (
                        <Icon
                            className="dynamic-delete-button"
                            type="minus-circle-o"
                            disabled={keys.length === 1}
                            onClick={() => this.remove(k)}
                        />
                    ) : null}
                </FormItem>
            );
        });
        return (
            <Card bordered={false}>
                <Form
                    onSubmit={this.handleSubmit}
                    hideRequiredMark
                >
                    <FormItem
                        {...formItemLayout}
                        label="属性名称"
                    >
                        {getFieldDecorator('attr_name', {
                            initialValue:  formInitValue.attr_name || '',
                            rules: [{
                                required: true, message: '请输入属性名称',
                            }],
                        })(
                            <Input placeholder="属性名称"/>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="所属商品类型"
                    >
                        {getFieldDecorator('cat_id', {
                            initialValue: formInitValue.cat_id || '',
                            rules: [{
                                required: true, message: '请选择商品类型',
                            }],
                        })(<Select placeholder="请选择">
                            <Option value="" >请选择</Option>
                            {SelectOption}
                            </Select>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="属性值录入方式"
                    >
                        {getFieldDecorator('attr_input_type', {
                            initialValue:  formInitValue.attr_input_type===0?0:(formInitValue.attr_input_type?formInitValue.attr_input_type:''),
                            rules: [{
                                required: true, message: '请选择编辑类型',
                            }],
                        })(
                            <Select placeholder="请选择" style={{width: '100%'}} onChange={this.handleSelectChange}>
                                <Option value="" >请选择</Option>
                                <Option value={0}>手动输入</Option>
                                <Option value={1}>选择输入</Option>
                                <Option value={2}>多行文本输入</Option>
                            </Select>
                        )}
                    </FormItem>
                    {formItems}
                    <FormItem {...formItemLayoutWithOutLabel}>
                        <Button type="dashed" onClick={this.add} style={{ width: '60%' }} ref="addAttr" >
                            <Icon type="plus" /> 添加属性值
                        </Button>
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="属性是否多选"
                    >
                        {getFieldDecorator('attr_type', {
                            initialValue: !formInitValue.attr_type ? 0 : 1,
                            rules: [{
                                required: true, message: '请选择',
                            }],
                        })(
                            <RadioGroup>
                                <Radio value={0}>否</Radio>
                                <Radio value={1}>是</Radio>
                            </RadioGroup>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="是否可以检索"
                    >
                        {getFieldDecorator('attr_index', {
                            initialValue: !formInitValue.attr_index ? 0 : 1,
                            rules: [{
                                required: true, message: '请选择',
                            }],
                        })(
                            <RadioGroup>
                                <Radio value={0}>不需要检索</Radio>
                                <Radio value={1}>关键字检索</Radio>
                                <Radio value={2}>范围检索</Radio>
                            </RadioGroup>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="顺序"
                    >
                        {getFieldDecorator('sort_order', {initialValue: formInitValue.sort_order || 100})(
                            <Input placeholder=""/>
                        )}<em className={styles.optional}>数字越大顺序越靠后</em>
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="是否关联"
                    >
                        {getFieldDecorator('is_linked', {
                            initialValue: !formInitValue.is_linked ? 0 : 1,
                            rules: [{
                                required: true, message: '请选择',
                            }],
                        })(
                            <RadioGroup>
                                <Radio value={1}>关联</Radio>
                                <Radio value={0}>不关联</Radio>
                            </RadioGroup>
                        )}
                    </FormItem>
                    <FormItem {...submitFormLayout} style={{marginTop: 32}}>
                        <Button type="primary" loading={submitting} onClick={this.handleSubmit.bind(this,editType,attr_id,attr_value_id)}>
                            提交
                        </Button>
                        <Button style={{marginLeft: 8}} onClick={this.handleParentModalVisible}>取消</Button>
                    </FormItem>
                </Form>
            </Card>
        );
    }
}
